package com.plugin.gocqhttp.configuration;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.*;
import org.springframework.context.annotation.AnnotationBeanNameGenerator;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.classreading.MetadataReader;

import java.io.IOException;
import java.util.Set;

/**
 * 扫描指定package下的类注册到beanfactroy
 */
public class EventHandlerRegistBeanFactory extends ClassPathScanningCandidateComponentProvider implements BeanDefinitionRegistryPostProcessor {

    private String ENVET_INIT_PACKAGE="com.plugin.gocqhttp.event.impl";
    private BeanNameGenerator beanNameGenerator = new AnnotationBeanNameGenerator();


    @Override
    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry) throws BeansException {
        Set<BeanDefinition> candidateComponents = findCandidateComponents(ENVET_INIT_PACKAGE);
        for (BeanDefinition beanDefinition : candidateComponents) {
            String beanName = beanNameGenerator.generateBeanName(beanDefinition, beanDefinitionRegistry);
            BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(beanDefinition, beanName);
            BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, beanDefinitionRegistry);
        }
    }

    @Override
    protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {
        return true;
    }

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {

    }
}
